<?php
    session_start();
	error_reporting(0);
//    error_reporting(E_ALL ^ E_NOTICE);
    header("Content-Type: text/html;charset=utf-8");
	$uid=(int)$_COOKIE['sys_uid'];
    include_once '../../includes/dbconn.php';
//	include_once '../../includes/dbconn.php';
    //应用APP ID
    $app_id = "101581816";
    //应用APP Key
    $app_secret = "423cd2f065d8ea32b80b4ecea2fcc4a6";
    //应用填写的网站回调域
    $my_url = "http://{$_SERVER['SERVER_NAME']}/api/qqlogin";//http://www.qyugroup.com/api/qqlogin/
    //echo $my_url;
    //exit();
    //Step1：获取Authorization Code

    $code = $_REQUEST["code"];//存放Authorization Code
    if(empty($code)) {
        //state参数用于防止CSRF攻击，成功授权后回调时原样带回
        $_SESSION['state'] = md5(uniqid(rand(), TRUE));
        //拼接URL
        $dialog_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$app_id."&redirect_uri=".urlencode($my_url)."&state=".$_SESSION['state'];
        echo("<script>top.location.href='".$dialog_url."'</script>");
    }

    //Step2：通过Authorization Code获取Access Token
    if($_REQUEST['state'] == $_SESSION['state'] || 1) {
        //拼接URL
        $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"."client_id=".$app_id."&redirect_uri=".urlencode($my_url)."&client_secret=".$app_secret."&code=".$code;
        $response = file_get_contents($token_url);

        //如果用户临时改变主意取消登录，返回true!==false,否则执行step3
        if (strpos($response, "callback") !== false) {
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);
            $msg = json_decode($response);
            if (isset($msg->error)) {
                echo "<h3>error:</h3>".$msg->error;
                echo "<h3>msg :</h3>".$msg->error_description;
                exit;
            }
        }

        //Step3：使用Access Token来获取用户的OpenID
        $params = array();
        parse_str($response, $params);//把传回来的数据参数变量化
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
        $str = file_get_contents($graph_url);
        if (strpos($str, "callback") !== false) {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str = substr($str, $lpos + 1, $rpos - $lpos -1);
        }
        $user = json_decode($str);//存放返回的数据 client_id ，openid
        if (isset($user->error)) {
            echo "<h3>error:</h3>".$user->error;
            echo "<h3>msg :</h3>".$user->error_description;
            exit;
        }

        //Step4：使用openid和access_token获取用户信息
        $user_data_url = "https://graph.qq.com/user/get_user_info?access_token={$params['access_token']}&oauth_consumer_key={$app_id}&openid={$user->openid}&format=json";

        $user_data = file_get_contents($user_data_url);//获取到的用户信息

        //以下为授权成功后的自定义操作
        if($user_data){
			$openid=$user->openid;
			$qqopenid=get_zd_name("qqopenid","users"," AND qqopenid='$openid'");
			setcookie("sys_qqopenid", $openid, time()+3600*24,"/");
//            echo "<pre>";
//            print_r($user_data);
//            echo "<pre>";
//            print_r($user);
			if($qqopenid){
				//echo "SELECT id,username,lastlogintime FROM `{$tablepre}users` WHERE qqopenid='$qqopenid'";
				//exit();
				$result = $db->sql_query("SELECT id,username,lastlogintime FROM `{$tablepre}users` WHERE qqopenid='$qqopenid'");
				if($bd=$db->sql_fetchrow($result)){
					$n=4;
					setcookie("sys_uid", $bd['id'], time()+3600*3*$n,"/");
					setcookie("sys_username", $bd['username'], time()+3600*3*$n,"/");
					setcookie("sys_lastlogintime", $bd['lastlogintime'], time()+3600*3*$n,"/");

					$sql="UPDATE `{$tablepre}users` SET logincount=logincount+1,loginip='$PHP_IP',lastlogintime='".time()."' WHERE qqopenid='$qqopenid' ";
					if($db->sql_query($sql)){
						JsGourl("/user.php");
						exit();
					}
				}
			}else{

                        JsGourl("/tel.php");

			}
			// ......
            //echo("<script> top.location.href='http://www.msllws.top'</script>");
        }else{
            echo '授权失败';
        }
    }else{
        echo("授权失败");
    }
	?>
